//
//  PickerOptionView.m
//  Foundation
//
//  Created by 新庭 on 2019/10/20.
//

#import "PickerOptionView.h"

@interface PickerOptionView () <UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) UIPickerView *pickerView;

@end

@implementation PickerOptionView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:CGRectMake(0, 0, UIScreen.jk_width, 216)]) {
        self.pickerView = [[UIPickerView alloc] init];
        [self addSubview:self.pickerView];
        [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_offset(0);
        }];
        
        self.pickerView.delegate = self;
        self.pickerView.dataSource = self;
    }
    return self;
}

- (void)setItems:(NSArray<OptionItem *> *)items {
    [super setItems:items];
    
    [self.pickerView reloadAllComponents];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex {
    [super setSelectedIndex:selectedIndex];
    [self.pickerView selectRow:selectedIndex inComponent:0 animated:YES];
}

- (NSUInteger)selectedIndex {
    return [self.pickerView selectedRowInComponent:0];
}

- (OptionItem *)selectedItem {
    return self.items[self.selectedIndex];
}

- (CGSize)intrinsicContentSize {
    return self.pickerView.intrinsicContentSize;
}

#pragma mark - Private
- (NSString *)itemString:(NSIndexPath *)ip {
    OptionItem *item = self.items[ip.row];
    return [self stringForItem:item];
}

#pragma mark - Picker View

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.items.count;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [self itemString:[NSIndexPath indexPathForRow:row inSection:component]];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    UIResponder *responder = self.nextResponder;
    if ([responder isKindOfClass:UITextField.class]) {
        UITextField *textField = (UITextField *)responder;
        textField.text = [self itemString:[NSIndexPath indexPathForRow:row inSection:component]];
    }
}

@end
